import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {AtIcon} from 'taro-ui';
import {View, Image, Swiper, SwiperItem, Button, Block, ScrollView} from '@tarojs/components'
import {vcmonitor} from "../../../utils/tools";
import {http} from "../../../utils/http";
import {
  SELLER_POSTER_LIST_INFO,
  SELLER_POSTER_ARR_LIST_INFO,
  RESOURCE_URL,
  TARO_ENV,
  IDENTITY, DEVELOP_CONTENT
} from "../../../constants/api";
import {user} from "../../../utils/user.service";
import GzhAuth from "../../../components/gzh-auth/gzh-auth";
import {h5Wx} from "../../../utils/h5.service";
import {platform} from "../../../utils/platform-settting.service";
import {UserIdentity} from "../../../utils/server.interface";
import {getContent} from "../../../utils/handlerPublicCode";
import './index.scss'

type PageOwnProps = {};
type PageState = {
  developContent: any
  loading: any
  toPromoteShow: boolean
  shareShow: boolean
  friendShow: boolean
  imgCustomizeList: any
  userIdentity: any
  sellerPosterList: any
  sellerImgList: any
  shareInfoList: any
  posterCurrent: any
  friendCurrent: any
}

class Index extends Component {
  state: PageState = {
    toPromoteShow: false,
    shareShow: false,
    friendShow: false,
    loading: true,
    userIdentity: UserIdentity | false,
    imgCustomizeList: [],
    sellerPosterList: [],
    sellerImgList: [],
    shareInfoList: [],
    developContent: false,
    friendCurrent: 0
  }

  async UNSAFE_componentWillMount() {
    vcmonitor(this)
    let userIdentity: any = {}
    const {siteId = '', from = '', isFirst = ''} = Taro.getCurrentInstance().router.params
    if (!from) {
      userIdentity = await http.get<UserIdentity>(IDENTITY, {})
    }
    let developContent
    if (siteId) {
      developContent = await http.carGet(DEVELOP_CONTENT, {sid: siteId})
    } else {
      developContent = await http.carGet(DEVELOP_CONTENT, {})
    }
    const sellerId = isFirst ? '' : userIdentity.sellerId // 发展一级分销商时链接不带sellerId
    if (!from && process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
      const shareData = {
        title: '加入我们',
        desc: '注册成为' + process.env.fxName,
        link: window.location.origin + '/common/distributor/invite/register?sellerId=' + sellerId + '&sid=' + userIdentity.siteId + '&sourceUserId=' + userIdentity.userId,
        imgUrl: platform.info.platformLogo
      }
      await h5Wx.share(shareData)
    }
    this.setState({userIdentity, developContent: developContent.content || '', loading: false})
    if (from) {
      return false
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      if (process.env.TARO_ENV !== 'h5') {
        Taro.showToast({
          title: '你还未登录，请登录',
          icon: 'none',
        })
      }
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }
    this.getData(isFirst)
  }

  onShareAppMessage() {
    const {friendCurrent, shareInfoList, userIdentity} = this.state;
    return {
      title: '邀你加入',
      path: '/common/distributor/invite/register?sellerId=' + userIdentity.sellerId + '&sid=' + userIdentity.siteId + '&sourceUserId=' + userIdentity.userId + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
      imageUrl: shareInfoList[friendCurrent]
    }
  }

  async getData(posterType) {
    const res = await http.HPost(SELLER_POSTER_LIST_INFO, {})
    if (res) {
      let imgCustomizeList = []
      if (res && res.data && res.data.imgCustomizeList) {
        imgCustomizeList = res.data.imgCustomizeList;
      }
      let sellerPosterList = []
      if (res && res.data && res.data.sellerPosterList) {
        sellerPosterList = res.data.sellerPosterList;
      }
      let shareInfoList = []
      if (res && res.data && res.data.shareInfoList) {
        shareInfoList = res.data.shareInfoList;
      }
      this.setState({
        imgCustomizeList: imgCustomizeList,
        sellerImgList: sellerPosterList,
        shareInfoList: shareInfoList
      }, async () => {
        const {sellerImgList} = this.state
        if (sellerImgList && sellerImgList.length > 0) {
          sellerImgList.map(async (item, index) => {
            const url = await http.HPost(SELLER_POSTER_ARR_LIST_INFO, {orderNo: index, posterType})
            if (url) {
              const {sellerPosterList} = this.state
              if (url.data.sellerPosterList[0]) {
                sellerPosterList.push(url.data.sellerPosterList[0])
              }
              this.setState({
                sellerPosterList
              })
            }
          })
        }
      })
    }
  }

  // 显示分享的遮罩层
  showShareLinks(type: number | string) {
    if (type === 0 && TARO_ENV === 'h5') {
      return this.setState({shareShow: true})
    }
    let friendShow = false;
    let toPromoteShow = false;
    if (type === 0) {
      friendShow = true;
    } else {
      toPromoteShow = true;
    }
    this.setState({
      friendShow,
      toPromoteShow
    });
  }

  // 关闭遮罩层
  close() {
    this.setState({
      friendShow: false,
      toPromoteShow: false
    });
  }

  // 保存图片
  async saveAlbum() {
    if (TARO_ENV === 'h5') {
      return false
    }
    const {sellerPosterList} = this.state;
    Taro.showLoading({title: '下载中...'})
    for (let i = 0; i <= sellerPosterList.length - 1; i++) {
      (function (t) {
        setTimeout(function () {
          Taro.getImageInfo({
            src: sellerPosterList[i],
          }).then((res) => {
            Taro.saveImageToPhotosAlbum({
              filePath: res.path,
            }).then(() => {
              if (i == sellerPosterList.length - 1) {
                Taro.hideLoading()
                Taro.showToast({title: '已保存' + (Number(i) + 1) + '张图片'})
              }
            }).catch(err => {
              Taro.hideLoading()
              console.log(err)
            })
          }).catch(err => {
            Taro.hideLoading()
            console.log(err)
          })
        }, 300 * t);
      })(i)
    }
  }

// 分享好友swiper滑动
  friendChange(e) {
    this.setState({
      friendCurrent: e.detail.current
    });
  }

  previewImage = (urls, current) => {
    Taro.previewImage({
      current: current, // 当前显示图片的http链接
      urls: [urls] // 需要预览的图片http链接列表
    })
  }

  getHistoryLength() {
    return window.history.length > 0
  }

  render() {
    const {
      loading,
      developContent,
      toPromoteShow,
      friendCurrent,
      friendShow,
      sellerPosterList,
      shareInfoList,
      shareShow
    } = this.state;
    return (
      <View className='distributor'>
        <GzhAuth />
        {!loading && <Block>{!developContent && <View>
          {process.env.TARO_ENV === 'h5' && this.getHistoryLength() &&
          <View className='history-back' onClick={() => Taro.navigateBack()}>
            <AtIcon value='icon icon-a-2tubiaozhizuomoban-01-011' color='#fff'
              customStyle='transform: rotate(90deg);vertical-align: inherit;' size='20px'
            />
          </View>}
          <Image src={`${RESOURCE_URL}/upload/images/20211008/1633677888166_191.png`} className='distributor-bg'
            mode='widthFix'
          />
        </View>}
          {developContent && <View>
            {process.env.TARO_ENV === "weapp" && <parser selectable html={developContent || ''} />}
            {process.env.TARO_ENV === "tt" && <rich-text preview selectable nodes={getContent(developContent)} />}
            {process.env.TARO_ENV === "h5" &&
            <View id='html-description' dangerouslySetInnerHTML={{__html: developContent}} />}
          </View>}
          <View className='customData-height' />
          <View className='distributor-footer'>
            <View className='distributor-footer-btn yellow' onClick={() => this.showShareLinks(0)}>获取专属邀请链接</View>
            <View className='distributor-footer-btn red' onClick={() => this.showShareLinks(1)}>获取专属邀请海报</View>
          </View>
          {/* 推广海报 */}
          {toPromoteShow && <View className='float-layout distributor-float-layout' onClick={() => this.close()}>
            <View className='float-layout-bottom' style='max-height: 90vh;height: -webkit-fill-available;'
              onClick={(e) => e.stopPropagation()}
            >
              <View className='posters-head bold'>
                推广海报
              </View>
              {sellerPosterList && sellerPosterList.length > 0 &&
              <View className='posters-swiper posters-swiper-promote'>
                <ScrollView scrollX className='subNav'>
                  <View className='nav-box'>
                    {sellerPosterList.map((item, index) =>
                      <View className='img-wrapper' key={index}>
                        <Image onClick={this.previewImage.bind(this, item, item)} src={item} mode='widthFix' className='posters-swiper-images' />
                      </View>
                    )}
                  </View>
                </ScrollView>
                <View className='swiper-item-group-footer'>
                  <View className='swiper-item-group-footer-btn bold'
                    onClick={this.saveAlbum.bind(this)}
                  >{TARO_ENV === 'h5' ? '长按图片保存到手机相册' : '保存到相册'}</View>
                </View>
              </View>}
              {sellerPosterList.length <= 0 && <View className='listNull'>
                <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' className='listNull_img' />
                <View className='text'>什么都没有,去看看别的吧~</View>
              </View>}
            </View>
          </View>}
          {/* 邀请好友 */}
          {friendShow && <View className='float-layout invite-frient-float-layout' onClick={() => this.close()}>
            <View className='float-layout-bottom' onClick={(e) => e.stopPropagation()}>
              <View className='posters-head bold'>
                邀请好友
              </View>
              <View className='posters-swiper posters-swiper-invite'>
                <Swiper
                  className='test-h'
                  autoplay={false}
                  current={friendCurrent}
                  onChange={this.friendChange.bind(this)}
                >
                  {shareInfoList && shareInfoList.map((item, index) =>
                    <SwiperItem className='w-80 p-lr-20 swiper-item-small' key={index}>
                      <Image onClick={this.previewImage.bind(this, item, item)} src={item} mode='widthFix'
                        className='posters-swiper-image'
                      />
                    </SwiperItem>
                  )}
                </Swiper>
                <View className='swiper-item-group-footer'>
                  <Button open-type='share' openType='share' className='share-button'>
                    <View className='swiper-item-group-footer-btn'>
                      <AtIcon prefixClass='car' size='24' value='iconweixin1' className='m-r-10' />
                      邀请微信好友
                    </View>
                  </Button>
                </View>
              </View>
            </View>
          </View>}
          {shareShow && <View className='share-lead'>
            <View className='img1'><Image src='https://resource.ivcheng.com/upload/images/20210824/1629807609008_91.png'
              className='img'
            /></View>
            <View className='img2'><Image src='https://resource.ivcheng.com/upload/images/20210824/1629807611682_62.png'
              className='img'
            /></View>
            <View onClick={() => this.setState({shareShow: false})} className='img3'><Image
              src='https://resource.ivcheng.com/upload/images/20210824/1629809872482_390.png' className='img'
            /></View>
          </View>}</Block>}
      </View>
    );
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
